package com.itheima.crm.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itheima.crm.dao.CustomerRepository;
import com.itheima.crm.domain.Customer;
import com.itheima.crm.service.CustomerService;

@Service
@Transactional
public class CustomerServiceImpl implements CustomerService{
	
	@Autowired
	private CustomerRepository customerRepository;

	@Override
	public List<Customer> findNoAssociationCustomer() {
		return customerRepository.findByFixedAreaIdIsNull();
	}

	@Override
	public List<Customer> findAssociationCustomer(String fixedAreaId) {
		return customerRepository.findByFixedAreaId(fixedAreaId);
	}

	@Override
	public void associationCustomersToFixedArea(String customerStr, String fixedAreaId) {
		customerRepository.clearByFixedAreaId(fixedAreaId);
		System.out.println("1111111111");
		if(StringUtils.isBlank(customerStr) || "null".equals(customerStr)){
			return;
		}
		String[] customerIds = customerStr.split(",");
		for (String id : customerIds) {
			customerRepository.updateByFixedAreaId(fixedAreaId,Integer.parseInt(id));
		}
		return;
	}

	@Override
	public void customerSignUp(Customer customer) {
		customerRepository.save(customer);
	}

	@Override
	public Customer customerCheckActiveCode(String telephone) {
		return customerRepository.findByTelephone(telephone);
	}

	@Override
	public void customerActive(String telephone) {
		customerRepository.updateByTelephone(telephone);
	}

	@Override
	public Customer customerLogin(String telephone, String password) {
		return customerRepository.findByTelephoneAndPassword(telephone,password);
	}

	@Override
	public Customer findById(String id) {
		return customerRepository.findOne(Integer.parseInt(id));
	}

}
